package com.example.linearlayoutdemo.avatar;

import android.app.Application;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;

public class ProfileViewModel extends AndroidViewModel {
    private AvatarRepository avatarRepository;
    private MutableLiveData<Bitmap> avatarLiveData = new MutableLiveData<>();
    private MutableLiveData<String> errorLiveData = new MutableLiveData<>();
    private String currentUserId;

    public ProfileViewModel(@NonNull Application application) {
        super(application);
        avatarRepository = new AvatarRepository(application);
        currentUserId = UserManager.getInstance().getCurrentUserId();
    }

    // 加载当前用户头像
    public void loadCurrentUserAvatar() {
        if (currentUserId == null) {
            errorLiveData.postValue("未找到用户信息");
            return;
        }

        avatarRepository.getAvatar(currentUserId, new AvatarRepository.AvatarCallback() {
            @Override
            public void onSuccess(Bitmap avatar, String path) {
                avatarLiveData.postValue(avatar);
            }

            @Override
            public void onFailure(String errorMessage) {
                errorLiveData.postValue(errorMessage);
            }
        });
    }

    // 保存当前用户选择的新头像
    public void saveNewAvatar(Uri imageUri) {
        if (currentUserId == null) {
            errorLiveData.postValue("未找到用户信息");
            return;
        }

        avatarRepository.saveAvatar(currentUserId, getApplication(), imageUri, 
                                  new AvatarRepository.AvatarCallback() {
            @Override
            public void onSuccess(Bitmap avatar, String path) {
                avatarLiveData.postValue(avatar);
            }

            @Override
            public void onFailure(String errorMessage) {
                errorLiveData.postValue(errorMessage);
            }
        });
    }

    // Getters
    public MutableLiveData<Bitmap> getAvatarLiveData() {
        return avatarLiveData;
    }

    public MutableLiveData<String> getErrorLiveData() {
        return errorLiveData;
    }
}
